package com.fary.beans.factory.xml;

import com.fary.core.io.ClassPathResource;
import com.fary.core.io.Resource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

import java.io.FileNotFoundException;
import java.io.IOException;

public class BeansDtdResolver implements EntityResolver {

    private static final String DTD_EXTENSION = ".dtd";

    private static final String DTD_NAME = "spring-beans";


    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws IOException {

        if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
            int lastPathSeparator = systemId.lastIndexOf('/');
            int dtdNameStart = systemId.indexOf(DTD_NAME, lastPathSeparator);
            if (dtdNameStart != -1) {
                String dtdFile = DTD_NAME + DTD_EXTENSION;
                try {
                    Resource resource = new ClassPathResource(dtdFile, getClass());
                    InputSource source = new InputSource(resource.getInputStream());
                    source.setPublicId(publicId);
                    source.setSystemId(systemId);
                    return source;
                } catch (FileNotFoundException ex) {
                    String s = "Could not resolve beans DTD [" + systemId + "]: not found in classpath";
                }
            }
        }

        // Fall back to the parser's default behavior.
        return null;
    }


    @Override
    public String toString() {
        return "EntityResolver for spring-beans DTD";
    }

}